package com.jfinal.weixin.sdk.api;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.lbs.model.CreateGEOData;
import com.jfinal.weixin.lbs.model.InLocationBean;
import com.jfinal.weixin.lbs.util.BaiduLBSUtil;
import com.jfinal.weixin.lbs.util.BaiduMapUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Jack.Zhou on 2015/12/21.
 */
public class BaiduLBSApi {

    public static String addPOIData(InLocationBean location, String openId) {
        ApiResult result = UserApi.getUserInfo(openId);
        int subscribe = result.getInt("subscribe");
        String nickname = result.getStr("nickname");
        int sex = result.getInt("sex");
        String language = result.getStr("language");
        String headimgurl = result.getStr("headimgurl");
        String remark = result.getStr("remark");
        int groupid = result.getInt("groupid");
        CreateGEOData data = new CreateGEOData();
        location = BaiduMapUtil.convertCoord(location);
        if (location.getAddress() == null || location.getAddress().isEmpty()) {
            JSONObject addressObject = BaiduLBSUtil.getRevertAddressByLocation(location);
            String formatted_address = addressObject.getJSONObject("result").getString("formatted_address");
            if (formatted_address != null && !formatted_address.isEmpty())
                location.setAddress(formatted_address);
        }
        data.setLatitude(Double.valueOf(location.getLatitude()));
        data.setLongitude(Double.valueOf(location.getLongitude()));
        data.setGeotable_id(BaiduLBSUtil.getTableId(BaiduLBSUtil.WECHAT_TABLE_NAME));
        data.setTitle(nickname);
        data.setCoord_type(BaiduLBSUtil.COORD_TYPE_BD);
        data.setTags(remark);
        data.setAk(PropKit.get(BaiduLBSUtil.AK));
        data.setAddress(location.getAddress());
        Map extData = new HashMap();
        extData.put("openId", openId);
        extData.put("headimgurl", headimgurl);
        if (userExists(openId)) {
            return BaiduLBSUtil.updatePOIData(data, extData);
        } else {
            return BaiduLBSUtil.createGEOData(data, extData);
        }
    }


    private static boolean userExists(String openId) {
        return BaiduLBSUtil.listGEOData(openId).getIntValue("size") > 0;
    }

}
